/*
 * Copyright (C) WeGuide 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package humrum.weguide.views;

import greendroid.app.GDListActivity;
import greendroid.graphics.drawable.ActionBarDrawable;
import greendroid.image.ImageProcessor;
import greendroid.widget.ActionBarItem;
import greendroid.widget.AsyncImageView;
import greendroid.widget.ItemAdapter;
import greendroid.widget.NormalActionBarItem;
import greendroid.widget.item.ProgressItem;
import humrum.weguide.R;
import humrum.weguide.net.Request;
import humrum.weguide.util.Strings;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListSearch extends GDListActivity implements OnScrollListener {

	/** ListView */
	private ListView listView;

	/** Search POI's using AsyncTask */
	private SearchPoi _taskSearch;

	/** PARAMS for search */
	private String _lat;
	private String _lgn;
	private String _raio;

	/** HashMap to popule list POI's */
	List<HashMap<String, String>> listHashMap = new ArrayList<HashMap<String, String>>();

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setFullscreen(true);

		setActionBarContentView(R.layout.list_all_layout);
		addItems();
		// extras
		_lat = this.getIntent().getExtras().getString("LAT");
		_lgn = this.getIntent().getExtras().getString("LNG");
		_raio = this.getIntent().getExtras().getString("RAIO");

		listView = (ListView) findViewById(R.id.list_view_poi);
		final ItemAdapter adapter = new ItemAdapter(this);
		adapter.add(new ProgressItem("", true));
		listView.setAdapter(adapter);

		searchAllPOI();
	}

	private void addItems() {
		// add Item MAP
		addActionBarItem(
				getActionBar().newActionBarItem(NormalActionBarItem.class)
						.setDrawable(
								new ActionBarDrawable(getResources(),
										R.drawable.map)),
				R.id.item_actionbar_map);
		// add Item Camera
		addActionBarItem(
				getActionBar().newActionBarItem(NormalActionBarItem.class)
						.setDrawable(
								new ActionBarDrawable(getResources(),
										R.drawable.camera)),
				R.id.item_actionbar_camera);
	}
	
	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		switch (item.getItemId()) {
		case R.id.item_actionbar_map:
			// start map
			return true;
		case R.id.item_actionbar_camera:
			// start camera
			return true;
		default:
			return super.onHandleActionBarItemClick(item, position);
		}		
	}

	public static class MyAdapter extends BaseAdapter implements ImageProcessor {

		private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		private final Rect mRectSrc = new Rect();
		private final Rect mRectDest = new Rect();

		private List<HashMap<String, String>> _list;

		static class ViewHolder {
			public AsyncImageView imageView;
			public TextView textView;
			public StringBuilder textBuilder = new StringBuilder();
		}

		private Bitmap mMask;
		private int mThumbnailSize;
		private int mThumbnailRadius;
		private LayoutInflater mInflater;

		/**
		 * Default construct
		 */
		public MyAdapter(Context context, List<HashMap<String, String>> list) {
			_list = list;
			mInflater = LayoutInflater.from(context);
			mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
			mThumbnailSize = context.getResources().getDimensionPixelSize(
					R.dimen.thumbnail_size);
			mThumbnailRadius = context.getResources().getDimensionPixelSize(
					R.dimen.thumbnail_radius);

			prepareMask();
		}

		private void prepareMask() {
			mMask = Bitmap.createBitmap(mThumbnailSize, mThumbnailSize,
					Bitmap.Config.ARGB_8888);

			Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint.setColor(Color.RED);
			paint.setStyle(Paint.Style.FILL_AND_STROKE);

			Canvas c = new Canvas(mMask);
			c.drawRoundRect(new RectF(0, 0, mThumbnailSize, mThumbnailSize),
					mThumbnailRadius, mThumbnailRadius, paint);
		}

		public int getCount() {
			return _list.size();
		}

		public Object getItem(int position) {
			return _list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.image_item_view,
						parent, false);
				holder = new ViewHolder();
				holder.imageView = (AsyncImageView) convertView
						.findViewById(R.id.async_image);
				holder.imageView.setImageProcessor(this);
				holder.textView = (TextView) convertView
						.findViewById(R.id.text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			@SuppressWarnings("unchecked")
			HashMap<String, String> item = (HashMap<String, String>) getItem(position);
			holder.imageView.setUrl(item.get("thumbs"));
			holder.textView.setText(item.get("poiName").toString());
			item = null;

			return convertView;
		}

		public Bitmap processImage(Bitmap bitmap) {
			Bitmap result = Bitmap.createBitmap(mThumbnailSize, mThumbnailSize,
					Bitmap.Config.ARGB_8888);
			Canvas c = new Canvas(result);

			mRectSrc.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
			mRectDest.set(0, 0, mThumbnailSize, mThumbnailSize);
			c.drawBitmap(bitmap, mRectSrc, mRectDest, null);
			c.drawBitmap(mMask, 0, 0, mPaint);

			return result;
		}

	}

	/** SCROOLLING ################################################# */

	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
	}

	public void onScrollStateChanged(AbsListView _listView, int scrollState) {
		if (listView == _listView) {
			searchAsyncImageViews(_listView,
					scrollState == OnScrollListener.SCROLL_STATE_FLING);
		}
	}

	private void searchAsyncImageViews(ViewGroup viewGroup, boolean pause) {
		final int childCount = viewGroup.getChildCount();
		for (int i = 0; i < childCount; i++) {
			AsyncImageView image = (AsyncImageView) viewGroup.getChildAt(i)
					.findViewById(R.id.async_image);
			if (image != null) {
				image.setPaused(pause);
			}
		}
	}

	/** ########################################################### */

	/**
	 * Start Async search nearby waypoints
	 * 
	 * @autor aderbal
	 */
	private void searchAllPOI() {
		final String url = Strings.URL_SEARCH_NEAR.replace("{LAT}", _lat)
				.replace("{LNG}", _lgn).replace("{RAIO}", _raio);
		_taskSearch = new SearchPoi();
		_taskSearch.execute(url);
	}

	/**
	 * Popule list<Hasmap> before search result ok
	 * 
	 * @param JSONArray
	 *            json
	 * 
	 * @author aderbal
	 */
	private void populeHashMap(JSONArray json) {
		// each json array
		int i = 0;
		for (; i < json.length(); i++) {
			try {
				HashMap<String, String> entity = new HashMap<String, String>();
				entity.put("poiid", json.getJSONObject(i).getString("id"));
				entity.put("poiName", json.getJSONObject(i).getString("name"));
				entity.put("owner", "");
				entity.put("thumbs", json.getJSONObject(i).getString("url"));
				entity.put("lat", json.getJSONObject(i).getString("lat"));
				entity.put("lng", json.getJSONObject(i).getString("lng"));
				listHashMap.add(entity);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		showListAdapter();
	}

	/**
	 * Show ListView populate
	 * 
	 * @autor aderbal
	 */
	private void showListAdapter() {
		Log.i(ListSearch.class.getName(), "Try clean layout and add list");
		listView.setAdapter(null);
		listView.setAdapter(new MyAdapter(this, listHashMap));
		listView.setOnScrollListener(this);
	}

	/**
	 * Class that makes the search of points from a URL so asynchronicity
	 * 
	 * @author aderbal
	 */
	private class SearchPoi extends AsyncTask<String, Integer, JSONArray> {
		private Request request;

		@Override
		protected JSONArray doInBackground(String... params) {
			request = new Request();
			return request.getData(params[0]);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			request = null;
		}

		@Override
		protected void onPostExecute(JSONArray result) {
			request.finish();
			if (result != null && result.length() > 0) {
				populeHashMap(result);
			} else {
				// noResultSearch();
			}
		}

	}
}
